//
//  SINAUserTitleDetaileViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2017/12/28.
//  Copyright © 2017年  androidlongs. All rights reserved.
//

#import "SINAUserTitleDetaileViewController.h"
#import "SINACustomPickView.h"
#import "SINAPhotoPopView.h"
#import "GetFilePath.h"
#import "SINAHttpRequestUtils.h"

@interface SINAUserTitleDetaileViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *titleImageView;

@end

@implementation SINAUserTitleDetaileViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#424242"];
}
-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.barTintColor = baseSelectColor;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleImageView.contentMode=UIViewContentModeScaleAspectFit;
//    self.navigationController.navigationBarHidden = YES;
    self.navigationItem.title = @"个人头像";
    UIBarButtonItem *askListButton = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStyleDone target:self action:@selector(alertTitleClickFunction)];
    [askListButton setImage:[UIImage imageNamed:@"ask_list"]];
    self.navigationItem.rightBarButtonItem = askListButton;
    
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.titleImageView andWithBlick:^(UIView *view) {
         [self showPhoneSelectFunction];
    }];
    
    
    
    SINAUserModel *userModel = [[SINACommonUserHelper share] getUserModel];
    //头像
    NSString *headerImageUrl = userModel.userTitleImageUrl;
    if (headerImageUrl!=nil&&headerImageUrl.length>1) {
        [self.titleImageView sd_setImageWithURL:[NSURL URLWithString:headerImageUrl]];
    }
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithHexString:@"#424242"];
}

-(void)alertTitleClickFunction
{
    [self showPhoneSelectFunction];
}

//退出页面功能
- (IBAction)backClickFunction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void) showPhoneSelectFunction{
    SINAPhotoPopView *popView =[[SINAPhotoPopView alloc]init];
    [popView show];
    __block typeof(self) bself = self;
    popView.creatPhopeBlock = ^{
        [bself openPhote:1];
        
    };
    popView.selectPhopeBlock = ^{
        [bself openPhote:2];
    };
    popView.savePhopeBlock = ^{
        //保存照片
        [bself loadImageFinished:bself.titleImageView.image];
    };
}
//修改点击功能
- (IBAction)alertTitleImageClickFuncton:(id)sender {
    [self showPhoneSelectFunction];
}
-(void)personSelectFunction{
    SINAPhotoPopView *popView =[[SINAPhotoPopView alloc]init];
    [popView show];
    __block typeof(self) bself = self;
    popView.creatPhopeBlock = ^{
        [bself openPhote:1];
        
    };
    popView.selectPhopeBlock = ^{
        [bself openPhote:2];
    };
    popView.savePhopeBlock = ^{
        //保存照片
        [bself loadImageFinished:bself.titleImageView.image];
        
    };
}
- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"已保存到像册" sureBtn:@"确定"
                                                         cancleBtn:nil];
    [alertView showXLAlertView];
    DLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}
-(void)openPhote :(NSInteger) flag{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.delegate = self;
    //可编辑
    picker.allowsEditing = YES;
    //判断是否可以打开照相机
    if (flag==1) {
        
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            //摄像头
            //UIImagePickerControllerSourceTypeSavedPhotosAlbum:相机胶卷
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        } else { //否则打开照片库
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
    }else{
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }
    [self presentViewController:picker animated:YES completion:nil];
}
//拍摄完成后要执行的代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
//    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaType; //指定用户选择的媒体类型
//    UIKIT_EXTERN NSString *const UIImagePickerControllerOriginalImage; // 原始图片
//    UIKIT_EXTERN NSString *const UIImagePickerControllerEditedImage; // 修改后的图片
//    UIKIT_EXTERN NSString *const UIImagePickerControllerCropRect; // 裁剪尺寸
//    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaURL; // 媒体的URL
//    UIKIT_EXTERN NSString *const UIImagePickerControllerReferenceURL NS_AVAILABLE_IOS(4_1); // 原件的URL
//    UIKIT_EXTERN NSString *const UIImagePickerControllerMediaMetadata //当数据来源是相机的时候获取到的静态图像元数据，可以使用phtoho框架进行处理
//    
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    
    NSData *data;
    
    if ([mediaType isEqualToString:@"public.image"]){
        
        //切忌不可直接使用originImage，因为这是没有经过格式化的图片数据，可能会导致选择的图片颠倒或是失真等现象的发生，从UIImagePickerControllerOriginalImage中的Origin可以看出，很原始，哈哈
        UIImage *originImage = [info objectForKey:UIImagePickerControllerEditedImage];
        
        //图片压缩，因为原图都是很大的，不必要传原图
        UIImage *scaleImage = [self scaleImage:originImage toScale:0.6];
        
        //以下这两步都是比较耗时的操作，最好开一个HUD提示用户，这样体验会好些，不至于阻塞界面
        if (UIImagePNGRepresentation(scaleImage) == nil) {
            //将图片转换为JPG格式的二进制数据
            data = UIImageJPEGRepresentation(scaleImage, 1);
        } else {
            //将图片转换为PNG格式的二进制数据
            data = UIImagePNGRepresentation(scaleImage);
        }
        
        //将二进制数据生成UIImage
        UIImage *image = [UIImage imageWithData:data];
        
        
        [self stopLoading];
        WeakSelf;
        [CXAFNHttpRequestUtils httpPostFileRequestWithParamters:nil withImage:image success:^(id responseData) {
            NSString *code = responseData[@"code"];
            [weakSelf stopLoading];
            if ([code isEqualToString:@"1000"]) {
                NSArray *imageArray = responseData[@"content"];
                if (imageArray!=nil&&imageArray.count>=1) {
                    NSString *titleImageUrl = imageArray[0];
                    [weakSelf alertUserTitle:titleImageUrl andImage:image];
                }else{
                    WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"上传头像数据异常" sureBtn:@"确定"
                                                                         cancleBtn:nil];
                    [alertView showXLAlertView];
                }
                
            }
        } failure:^(NSError *error, NSInteger code) {
            [weakSelf stopLoading];
            
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"上传头像失败" sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
        }];
    }
    
}

//修改用户头像
-(void) alertUserTitle:(NSString *) titleUrl andImage:(UIImage *)image{
    //登录请求参数
    
    SINAUserModel *userModel =[[SINACommonUserHelper share]getUserModel];
    if (userModel==nil) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"更新头像失败" message:@"用户信息异常" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:userModel.userUid forKey:@"uuid"];
    [dict setObject:titleUrl forKey:@"headimg"];
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    
    
    [self startLoading];
    WeakSelf;
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,userAlertInformationUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        [weakSelf stopLoading];
        if ([code isEqualToString:@"1000"]) {
//            NSDictionary *result = responseData[@"content"];
            
            weakSelf.titleImageView.image =image;
            
            SINAUserModel *userModel=[[SINACommonUserHelper share]getUserModel];
            userModel.userTitleImageUrl=titleUrl;
            [[SINACommonUserHelper share]saveUserModel:userModel];
            
            
            
        }else if ([code isEqualToString:@"1003"]) {
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"验证失败" sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }else{
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定" cancleBtn:nil];
            [alertView showXLAlertView];
        }
        
        
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"验证失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
    }];
}


#pragma mark- 缩放图片
-(UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
